package longfly.development;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import casio.serial.SerialPort;

import longfly.development.Print_Setup.insert_Thread;
import longfly.development.R.drawable;
import longfly.development.R.id;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Debug;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class Table2 extends Activity {
	
	TextView	ALL_TABLE,ALL_TABLE_TEXT;
	TextView	ALL_FREE_TABLE,ALL_FREE_TABLE_TEXT;
	TextView	ALL_BUSY_TABLE,ALL_BUSY_TABLE_TEXT;
	
	
	GridView	GRIDVIEW_TABLE;
	Button		FRONTPAGE;
	Button		NEXTPAGE;
	TextView	NOWPAGE;
	TextView	ALLPAGE;
	Button		LOGINOUT;
	ListView	TABLE_TYPE_LIST,TABLE_QY_LIST;
	LinearLayout	TABLE_LV;
	ImageView	INOUTPIC;
	/***************以下是窗口里的控件***********************/
	Button		NUM_OK;	
	EditText	FIND_TABLE_NUM;
	/*********以下是对话框里的控件***********/
	
	Button	    DAILOG_BTN_KAITAI;	
	Button	    DAILOG_BTN_DIANCAI;	
	Button	    DAILOG_BTN_JIACAI;	
	Button	    DAILOG_BTN_CHACAI;	
	Button	    DAILOG_BTN_JIEZHANG;	
	Button	    DAILOG_BTN_XIAOTAI;	
	Button	    DAILOG_BTN_ZHUANTAI;	
	Button	    DAILOG_BTN_CUICAI;	

	TextView	DAILOG_TEXT_TABLE_NUM;
	TextView	DAILOG_TEXT_TABLE_SELLNUM;
	
	
	String		Share_Table_Num;	
	String		Share_Table_State;		
	String 		num = null ;			
	String[] Table_Type_Name ,Table_Type_Code;
	/*********以上是对话框里的控件***********/
	/**************************************/
	TextView	DAILOG_CHECK_TEXT_TAIHAO;
	TextView	DAILOG_CHECK_TEXT_DANHAO;
	TextView	DAILOG_CHECK_TEXT_KAITAISHIJIAN;
	TextView	DAILOG_CHECK_TEXT_RENSHU;
	TextView	DAILOG_CHECK_TEXT_KAITAIREN;
	TextView	DAILOG_CHECK_TEXT_XIAOFEI;
	TextView	DAILOG_CHECK_TEXT_JIASHOU;
	TextView	DAILOG_CHECK_TEXT_ZHEKOU;
	TextView	DAILOG_CHECK_TEXT_ZONGJI;
	TextView	DAILOG_CHECK_TEXT_YINGSHOU;
	TextView	DAILOG_CHECK_TEXT_XIANSJIN;
	TextView	DAILOG_CHECK_TEXT_ZHAOLING;
	TextView	DAILOG_CHECK_TEXT_KAOHAO;
	TextView	DAILOG_CHECK_TEXT_JIFEN;
	TextView	DAILOG_CHECK_TEXT_KAYUKE;
	TextView	DAILOG_CHECK_TEXT_LEIXING;
	
	Button		DAILOG_BTN_CHECK_SK;
	Button		DAILOG_BTN_CHECK_0 ;	
	Button		DAILOG_BTN_CHECK_1 ;	
	Button		DAILOG_BTN_CHECK_2 ;	
	Button		DAILOG_BTN_CHECK_3 ;	
	Button		DAILOG_BTN_CHECK_4 ;	
	Button		DAILOG_BTN_CHECK_5 ;	
	Button		DAILOG_BTN_CHECK_6 ;	
	Button		DAILOG_BTN_CHECK_7 ;	
	Button		DAILOG_BTN_CHECK_8 ;	
	Button		DAILOG_BTN_CHECK_9 ;	
	Button		DAILOG_BTN_CHECK_CLEAR ;	
	Button		DAILOG_BTN_CHECK_DEL ;	
	Button		DAILOG_BTN_CHECK ;	
	Button		DAILOG_BTN_EXIT ;	
	
	String	CheckTitle,CheckTableNum,CheckNum,CheckContent,CheckDanhao,
		CheckXiaoFeiZongJia,CheckJiaShou,CheckYingShou,CheckXianJinShiSHou,
		CheckZhaoLing,CheckUser,CheckDateTime;
	boolean	Check_b1_1,Check_b1_2,Check_b1_3,Check_b1_4,Check_b1_5,Check_b1_6,Check_b1_7;
	boolean	Check_b2_1,Check_b2_2,Check_b2_3,Check_b2_4,Check_b2_5,Check_b2_6,Check_b2_7,Check_b2_8,Check_b2_9,Check_b2_10,Check_b2_11,Check_b2_12;
	boolean	Check_b3_1,Check_b3_2,Check_b3_3,Check_b3_4,Check_b3_5,Check_b3_6,Check_b3_7,Check_b3_8,Check_b3_9,Check_b3_10,Check_b3_11,Check_b3_12;
	/*********以下是开台对话框里的控件***********/	
	Button	    DAILOG_BTN_KAITAI2;	
	Button	    DAILOG_BTN_DIANCAI2;	
	Button	    DAILOG_BTN_CANCEL;	
	
	Button		DAILOG_BTN_PER_0;
	Button		DAILOG_BTN_PER_1;
	Button		DAILOG_BTN_PER_2;
	Button		DAILOG_BTN_PER_3;
	Button		DAILOG_BTN_PER_4;
	Button		DAILOG_BTN_PER_5;
	Button		DAILOG_BTN_PER_6;
	Button		DAILOG_BTN_PER_7;
	Button		DAILOG_BTN_PER_8;
	Button		DAILOG_BTN_PER_9;
	Button		DAILOG_BTN_PER_DEL;
	
	TextView	DAILOG_TEXT_PERSON_NUM;				
	TextView	DAILOG_TEXT_DANHAO;				
	/*********以上是对话框里的控件***********/
	
	private	int Dispay_widthPixels;
   	private int DIALOG_FIND=101;
   	private int DIALOG_KAITAI=102;
   	private int DIALOG_JIEZHANG=103;
	private List<Grid_Item_Table> mylist;
	private	GridItemTableSQLAdapter	adapterr;
    private ArrayList<HashMap<String,String>> list=null;	//已点菜品的listview
    private HashMap<String,String>map=null;	//已点菜品
	SimpleAdapter list_adapter;	
	SQLiteDatabase db;
	String	UserLimit;
	String	UserCode;
	protected OutputStream mOutputStream;		//串口输出描述
    private final int UPDATE_UI = 1;
    boolean	ref_if = true;
    Handler mHandler; 
    int ALLTABLE = 0;
    
    int nowpage = 1;
    int PageSize = 30;
    int pageID = 1;
    String TABLE_NAME = "lfcy_base_tableinf";
    String SQL_String_DEFINE = "select * from "+ TABLE_NAME;
    String type_class = null;

    private GestureDetector mGestureDetector;      
    private LinkedHashMap<String, Integer> mRecordMap = new LinkedHashMap<String, Integer>();  
    boolean	showornot = false;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		DisplayMetrics displaysMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics( displaysMetrics );
        Dispay_widthPixels=displaysMetrics.widthPixels;	//以上是初始化一个UI像素的描述！
        long	startTime =	Debug.threadCpuTimeNanos(); 
		switch (Dispay_widthPixels) {	//根据屏幕的横向像素来加载不通的UI界面！
			case 800:
		        setContentView(R.layout.i800_table);
		        break;
			case 1024:
		        setContentView(R.layout.i800_table);
				break;
			default:
		        setContentView(R.layout.i800_table);
				break;
		}          
        long	endXMLTime =	Debug.threadCpuTimeNanos(); 
		Log.i("info", "执行setContentView(R.layout.i800_table)用时"+(endXMLTime - startTime) +"纳秒");  
		db = SQLiteDatabase.openOrCreateDatabase(this.getFilesDir().toString()+"/Android_POS.db3", null);

		find_id();
        key_things();
        init_Table_Type_and_Quyu(); //初始化做台状态和区域数组的！
//        init_grid(1);
        RefreshGrid(1,SQL_String_DEFINE , null);
        Refresh_State();
        init_data();		//初始化从上一页获取的导入数据
        init_list();
        init_AllTable();
        //启动刷新桌台的线程
        mHandler = new MyHandler();//创建Handler 
        time_ref.start();

        long	endLoadTime =	Debug.threadCpuTimeNanos(); 
		Log.i("info", "载入数据用时"+(endLoadTime - endXMLTime) +"纳秒");  
		
        mGestureDetector = new GestureDetector(this, new DefaultGestureListener());  
    }

	private void init_AllTable() {
		// TODO Auto-generated method stub
		int	All_Table=0;
		//查全部的桌台
		try {
    		Cursor  cursor = db.rawQuery("select * from lfcy_base_tableinf", null);
			while (cursor.moveToNext()) {
				All_Table ++;
			}
			ALL_TABLE.setText(""+All_Table);
			cursor.close();
		} catch (Exception e) {
			ALL_TABLE.setText("");
		}	
		ALLTABLE = All_Table;
	}

	private void init_list() {
		// TODO Auto-generated method stub
		init_table_type();
		init_table_quyu();
	}
	
	/**************桌台区域部分************************/
	private void init_table_quyu() {
		String	sql= "select * from lfcy_base_tablearea";     

		try {
			Cursor  cursor = db.rawQuery( sql, null);
			fill_hashmap_typeclass(cursor);
			inflateList_quyuclass(cursor);	
		} catch (Exception e) {
			// TODO: handle exception
		}		
	}

	private void inflateList_quyuclass(Cursor cursor) {
		// TODO Auto-generated method stub
		 //将数据与adapter集合起来
		list_adapter = new SimpleAdapter(
      		this, 
			list, 
			R.layout.i800_bigclass_list 
			, new String[]{"cName"}
			, new int[]{id.table_list_2 }
		);
		
		//显示数据
		TABLE_QY_LIST.setAdapter(list_adapter);			
	}

	/***************桌台类型部分***********************/
	private void init_table_type() {	
		String	sql= "select * from lfcy_base_tabletype";     

		try {
			Cursor  cursor = db.rawQuery( sql, null);
			fill_hashmap_typeclass(cursor);
			inflateList_typeclass(cursor);	
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	private void inflateList_typeclass(Cursor cursor) {
		// TODO Auto-generated method stub
		 //将数据与adapter集合起来
		list_adapter = new SimpleAdapter(
      		this, 
			list, 
			R.layout.i800_bigclass_list 
			, new String[]{"cName"}
			, new int[]{id.table_list_2}
		);
		
		//显示数据
		TABLE_TYPE_LIST.setAdapter(list_adapter);		
	}

	private ArrayList fill_hashmap_typeclass(Cursor cursor) {
		// TODO Auto-generated method stub
	    list=new ArrayList<HashMap<String,String>>();
		int i=0;
		while(cursor.moveToNext()) 
		{
		  i++;
          map=new HashMap<String,String>();
         
          map.put("_id", cursor.getString(cursor.getColumnIndex("_id")));
          map.put("cName", cursor.getString(cursor.getColumnIndex("cName")));
          map.put("cCode", cursor.getString(cursor.getColumnIndex("cCode")));
			
		  list.add(map);
		}		
		return list;
	}

	/*************桌台类型部分结束*************************/

	@Override
    protected void onResume() {
    	// TODO Auto-generated method stub
    	super.onResume();
//        init_grid(1);
        RefreshGrid(1,SQL_String_DEFINE , null);
        Refresh_State();   
        ref_if = true;
        System.out.println("onResume");
    }

    /********************定时刷新桌台的线程开启*********************************************/
	MyThread time_ref = new MyThread();		//接收PC端数据的线程

	//接收PC端数据的线程
	class MyThread extends Thread 
	{  

		public void run() 
		{
			Time_Ref();
		}
	}   
    

	private void Time_Ref() {
		// TODO Auto-generated method stub
		for(;;)
		{
			try {
				Thread.sleep(1000);
		    	if(ref_if)
		    	{
	                //UPDATE是一个自己定义的整数，代表了消息ID 
	                Message msg = mHandler.obtainMessage(UPDATE_UI); 
	                mHandler.sendMessage(msg); 
//	                System.out.println(" ref_if = true");
		    	}
		    	else{
//		            System.out.println(" ref_if = flash");
		    	}
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 			
		}	
	}	
	
    private class MyHandler extends Handler 
    {

        @Override 
        public void handleMessage(Message msg) { 
            // TODO Auto-generated method stub 
            super.handleMessage(msg); 
            switch(msg.what) 
            { 
	            case UPDATE_UI://在收到消息时，对界面进行更新 	            		                
	  				pageID = nowpage;
	            	if (type_class == null)
	            	{
//	            		init_grid(nowpage);

	            		String[] Sql_String_condition = { type_class};	
						SQL_String_DEFINE = "select * from "+ TABLE_NAME;
			   	        RefreshGrid(pageID ,SQL_String_DEFINE , null);
	            	}else{
						String[] Sql_String_condition = { type_class};	
						RefreshGrid(pageID, SQL_String_DEFINE ,Sql_String_condition);						
		                Refresh_State();  
	            	}	
 
	                break; 
            } 
        } 
    }
    /********************定时刷新桌台的线程结束*********************************************/
	private void init_data() {
		// TODO Auto-generated method stub
		Bundle bundle=getIntent().getExtras();
		  //获取Bundle的信息
		UserCode = bundle.getString("UserCode");
		UserLimit  = bundle.getString("UserLimit");
	}
	
    //刷新桌面的空闲台数
	private void Refresh_State() {
		// TODO Auto-generated method stub
		int	Free_Table=0;
		String[]	Sql_String_condition = { "1" };	

		//空闲部的桌台
		try {
    		Cursor  cursor = db.rawQuery("select * from lfcy_base_tableinf where iTableState = ?", Sql_String_condition);
			while (cursor.moveToNext()) {
				Free_Table ++;
			}
			ALL_FREE_TABLE.setText(""+Free_Table);
			ALL_BUSY_TABLE.setText(""+( ALLTABLE- Free_Table));
			cursor.close();
		} catch (Exception e) {
			ALL_FREE_TABLE.setText("");
		}
	}

	 
    private void init_Table_Type_and_Quyu() {
		// TODO Auto-generated method stub
 	    Cursor  cursor = db.rawQuery("select * from lfcy_base_tabletype", null);
		Table_Type_Name = new String[cursor.getCount()];
		Table_Type_Code = new String[cursor.getCount()];
 	    int i=0;
		while(cursor.moveToNext()) {
			Table_Type_Name[i] = cursor.getString(cursor.getColumnIndex("cName"));		
			Table_Type_Code[i] = cursor.getString(cursor.getColumnIndex("cCode"));		
			i++;
		}		
	}
	private int Traversal(String[] Table_Where_Code, String string) {
		// TODO Auto-generated method stub
		int i = 0;
		for (int j = 0; j < Table_Where_Code.length; j++) {
			if( Table_Where_Code[j].trim().equals(string) )
			{
				i = j;
			}	
		}
		return i;			
	}   
	private void init_grid( int pageID ) {	//当前页数
		mylist = new ArrayList<Grid_Item_Table>();
		SQL_String_DEFINE = "select * from " + TABLE_NAME +     
        " Limit "+String.valueOf(PageSize)+ " Offset " +String.valueOf( (pageID-1)*PageSize); 
		try {
    		Cursor  cursor = db.rawQuery( SQL_String_DEFINE , null);
			while (cursor.moveToNext()) 
			{
				Grid_Item_Table picture = new Grid_Item_Table();
				picture.setImageId(cursor.getInt(cursor
						.getColumnIndex("iTableState")));
				picture.setTableState(cursor.getString(cursor
						.getColumnIndex("iTableState")));	//桌台的状态（空闲还是开台）
				picture.setTime(cursor.getString(cursor
						.getColumnIndex("iTabletime")));	//开台的时间			
				picture.setNumber(cursor.getString(cursor
						.getColumnIndex("iTableNumber")));	//台号
				int num = Traversal(Table_Type_Code,cursor.getString(cursor.getColumnIndex("iTableClass")));				
				picture.setTablePlace(Table_Type_Name[num]);	//桌台类型（大厅还是包厢）
				picture.setTablePersonNumber(cursor.getString(cursor
						.getColumnIndex("iTablePerson")));	//可容纳人数
				picture.setTable_PersonNumber(cursor.getString(cursor
						.getColumnIndex("iTable_Person")));	//可容纳人数

				mylist.add(picture);
			}
			NOWPAGE.setText(""+pageID);
			if (pageID == 1)
				ALLPAGE.setText(   String.valueOf( cursor.getCount()/30 + 1 )   );
			cursor.close();
		} catch (Exception e) {
			// TODO: handle exception
		}

		adapterr = new GridItemTableSQLAdapter(mylist, this , Dispay_widthPixels);// 自定义适配器
		GRIDVIEW_TABLE.setAdapter(adapterr);
	}

	
	protected void RefreshGrid(int page , String mySQL_String , String[] Sql_String_condition) {
		// TODO Auto-generated method stub
		// 用于初始化
		mylist = new ArrayList<Grid_Item_Table>();
	    String mysqlstring = " Limit "+String.valueOf(PageSize)+ " Offset " + String.valueOf( (page-1)*PageSize);
	    mySQL_String = mySQL_String + mysqlstring;
	    
		try {
    		Cursor  cursor = db.rawQuery(mySQL_String, Sql_String_condition);
			while (cursor.moveToNext()) {
				Grid_Item_Table picture = new Grid_Item_Table();
				picture.setImageId(cursor.getInt(cursor
						.getColumnIndex("iTableState")));
				picture.setTableState(cursor.getString(cursor
						.getColumnIndex("iTableState")));	//桌台的状态（空闲还是开台）
				picture.setTime(cursor.getString(cursor
						.getColumnIndex("iTabletime")));	//开台的时间			
				picture.setNumber(cursor.getString(cursor
						.getColumnIndex("iTableNumber")));	//台号
				int num = Traversal(Table_Type_Code,cursor.getString(cursor.getColumnIndex("iTableClass")));				
				picture.setTablePlace(Table_Type_Name[num]);	//桌台类型（大厅还是包厢）
				picture.setTablePersonNumber(cursor.getString(cursor
						.getColumnIndex("iTablePerson")));	//可容纳人数
				picture.setTable_PersonNumber(cursor.getString(cursor
						.getColumnIndex("iTable_Person")));	//可容纳人数

				mylist.add(picture);
			}
			cursor.close();
			NOWPAGE.setText(""+pageID);
			if (pageID == 1)
				ALLPAGE.setText(   String.valueOf( cursor.getCount()/30 + 1 )   );

		} catch (Exception e) {
			// TODO: handle exception
		}

		adapterr = new GridItemTableSQLAdapter(mylist, this , Dispay_widthPixels);// 自定义适配器
		GRIDVIEW_TABLE.setAdapter(adapterr);		
	}

	private void key_things() {
		// TODO Auto-generated method stub
		 GRIDVIEW_TABLE.setOnItemClickListener(new OnItemClickListener()   
         {   
             public void onItemClick(AdapterView<?> parent, View v, int position, long id)   
             {   
                 Share_Table_Num 	=	mylist.get(position).getNumber();
                 Share_Table_State	=	mylist.get(position).getSringTableState();
                 Integer intObj = new Integer( Share_Table_State );
			   	 int i = intObj.intValue();
			   	 if (i == 1) {
	                 showDialog(DIALOG_KAITAI);					
			   	 } else {
	                 showDialog(DIALOG_FIND);
			   	 }   
             }  
         });     

			TABLE_TYPE_LIST.setOnItemClickListener(new OnItemClickListener()   
	         {   
	             public void onItemClick(AdapterView<?> parent, View v, int position, long id)   
	             {   
	  				HashMap<String,String> map = (HashMap<String,String>)parent.getItemAtPosition(position);
	  				type_class =	String.valueOf(map.get("cCode"));   
	  				System.out.println("type_class == "+ type_class);
	  				
	  				pageID = nowpage = 1;

	  				SQL_String_DEFINE = "select * from "+ TABLE_NAME +" where iTableClass = ?";
					String[] Sql_String_condition = { type_class};	
					RefreshGrid(1 ,SQL_String_DEFINE ,Sql_String_condition);	
			   	}  
	         }); 
			
			TABLE_QY_LIST.setOnItemClickListener(new OnItemClickListener()   
	         {   
	             public void onItemClick(AdapterView<?> parent, View v, int position, long id)   
	             {   
	  				HashMap<String,String> map = (HashMap<String,String>)parent.getItemAtPosition(position);
	  				type_class =	String.valueOf(map.get("cCode"));   
	  				System.out.println("type_class == "+ type_class);
	  				
	  				pageID = nowpage = 1;

	  				SQL_String_DEFINE = "select * from "+ TABLE_NAME +" where iTableClass2 = ?";
					String[] Sql_String_condition = { type_class};	
					RefreshGrid(1 ,SQL_String_DEFINE ,Sql_String_condition);	
			   	}  
	         }); 
			
			FRONTPAGE.setOnClickListener(new OnClickListener()
		    {
			   	@Override
			   	public void onClick(View v)
			   	{	
			   		Integer intObj = new Integer( NOWPAGE.getText().toString() );
			   	    int i = intObj.intValue();	
			   	    if(i == 1)
			   	    {
			   	    	Toast.makeText(Table2.this, "已经是最前一页了", Toast.LENGTH_SHORT).show();
			   	    }
			   	    else
			   	    {	
//			   	    	init_grid( i-1);
			   	    	pageID = i-1;
			   	    	NOWPAGE.setText(""+(i-1));
			   	    	nowpage = i-1;
			   	        RefreshGrid(nowpage ,SQL_String_DEFINE , null);
			   	        type_class = null;
			   	    }	
			   	}
		    });	
			NEXTPAGE.setOnClickListener(new OnClickListener()
		    {
			   	@Override
			   	public void onClick(View v)
			   	{	
			   		Integer intObj = new Integer( NOWPAGE.getText().toString() );
			   	    int i = intObj.intValue();	

			   		intObj = new Integer( ALLPAGE.getText().toString() );
			   	    int j = intObj.intValue();	
			   	    
			   	    if(i == j)
			   	    {
			   	    	Toast.makeText(Table2.this, "已经是最后一页了", Toast.LENGTH_SHORT).show();
			   	    }
			   	    else
			   	    {	
			   	    	pageID = i+1;
			   	    	NOWPAGE.setText(""+(i+1));
			   	    	nowpage = i+1;
			   	        RefreshGrid(nowpage ,SQL_String_DEFINE , null);
			   	        type_class = null;
			   	    }				   	 
			   	}
		    });	
			
			INOUTPIC.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
		        	if (showornot) {
		        		TABLE_LV.setVisibility(View.GONE);
		        		INOUTPIC.setBackgroundResource(drawable.in2out);
		        		showornot = false;
					}
		        	else {
		        		TABLE_LV.setVisibility(View.VISIBLE);
		        		INOUTPIC.setBackgroundResource(drawable.out2in);
		        		showornot = true;
					}					
				}
			});
			
			LOGINOUT.setOnClickListener(new OnClickListener() {				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					db.close();
					finish();
				}
			});
			
			ALL_TABLE.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
				    SQL_String_DEFINE = "select * from "+ TABLE_NAME;
				    type_class = null;
		   	        RefreshGrid(nowpage ,SQL_String_DEFINE , null);
				}
			});
			ALL_TABLE_TEXT.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
				    SQL_String_DEFINE = "select * from "+ TABLE_NAME;
				    type_class = null;
		   	        RefreshGrid(nowpage ,SQL_String_DEFINE , null);
				}
			});
			
			ALL_FREE_TABLE.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
				    SQL_String_DEFINE = "select * from lfcy_base_tableinf where iTableState = ?";
				    type_class = "1";
			   		String[]	Sql_String_condition = { type_class };	
		   	        RefreshGrid(1 ,SQL_String_DEFINE , Sql_String_condition);
				}
			});
			ALL_FREE_TABLE_TEXT.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
				    SQL_String_DEFINE = "select * from lfcy_base_tableinf where iTableState = ?";
				    type_class = "1";
			   		String[]	Sql_String_condition = { type_class };	
		   	        RefreshGrid(1 ,SQL_String_DEFINE , Sql_String_condition);
				}
			});
			
			ALL_BUSY_TABLE.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
				    SQL_String_DEFINE = "select * from lfcy_base_tableinf where iTableState = ?";
				    type_class = "2";
			   		String[]	Sql_String_condition = { type_class };	
		   	        RefreshGrid(1 ,SQL_String_DEFINE , Sql_String_condition);
				}
			});
			ALL_BUSY_TABLE_TEXT.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
				    SQL_String_DEFINE = "select * from lfcy_base_tableinf where iTableState = ?";
				    type_class = "2";
			   		String[]	Sql_String_condition = { type_class };	
		   	        RefreshGrid(1 ,SQL_String_DEFINE , Sql_String_condition);
				}
			});
			
			NUM_OK.setOnClickListener(new OnClickListener()
		    {
			   	@Override
			   	public void onClick(View v)
			   	{	
			   		num =  FIND_TABLE_NUM.getText().toString();
	  				pageID = 1;
	  				SQL_String_DEFINE = "select * from "+ TABLE_NAME +" where iTableNumber = ?";
	  				type_class = ""+num;
			   		String[]	Sql_String_condition = { type_class };	
					RefreshGrid(1,SQL_String_DEFINE ,Sql_String_condition);					
			   		FIND_TABLE_NUM.setText("");	
			   		
			   		if(num.trim().equals("0716"))
			   		{
			   			finish();
			   		}	
			   	}
		    });		

	}

	private void find_id() {
		// TODO Auto-generated method stub
		GRIDVIEW_TABLE	= (GridView) findViewById(id.all_tables);
		ALL_TABLE 		= (TextView) findViewById(id.table_all);
		ALL_TABLE_TEXT 	= (TextView) findViewById(id.table_all_text);
		ALL_FREE_TABLE	= (TextView) findViewById(id.table_free);
		ALL_FREE_TABLE_TEXT	= (TextView) findViewById(id.table_free_text);
		ALL_BUSY_TABLE	= (TextView) findViewById(id.table_busy);
		ALL_BUSY_TABLE_TEXT	= (TextView) findViewById(id.table_busy_text);
		FRONTPAGE		= (Button) 	 findViewById(id.table_page_front);
		NEXTPAGE		= (Button) 	 findViewById(id.table_page_next);
		NOWPAGE			= (TextView) findViewById(id.table_page_now);
		ALLPAGE			= (TextView) findViewById(id.table_page_all);
		LOGINOUT		= (Button) 	findViewById(id.table_loginout);

		NUM_OK			= (Button) findViewById(id.table_btn_ok);
		FIND_TABLE_NUM	= (EditText) findViewById(id.table_edit_num);
		
		TABLE_TYPE_LIST	= (ListView) findViewById(id.table_type_list);
		TABLE_QY_LIST	= (ListView) findViewById(id.table_quyu_list);
		TABLE_LV	=	(LinearLayout)findViewById(id.table_ly);
		INOUTPIC	=	(ImageView) findViewById(id.table_in_out_pic);
	}

	//我的打印机打印字符串的方法！！第一个参数是命令字！倍高倍宽之类！第二个参数是要打印的字符串！
	protected void print_String(boolean print_if,boolean weight,boolean height,  String in_String) {
		// TODO Auto-generated method stub
		if (print_if) {
			int i;
			byte[] prt_code_buffer;
	   		byte[] cancel_to_normal = {0x0a, 0x1b, 0x21,0x00};//取消倍高倍宽
	   		byte[] double_height    = {0x0a, 0x1b, 0x21,0x10};//倍高
	   		byte[] double_weight    = {0x0a, 0x1b, 0x21,0x20};//倍宽
	   		byte[] double_hweight   = {0x0a, 0x1b, 0x21,0x30};//倍高倍宽
	   		
	   		if (weight) {
				if (height) {
					prt_code_buffer = double_hweight;	//又倍宽 又倍高
				} else {
					prt_code_buffer = double_weight;	//又倍宽 但是不倍高
				}
			} else {
				if (height) {
					prt_code_buffer = double_height;	//不倍宽 但是倍高
				} else {
					prt_code_buffer = cancel_to_normal;	//不倍宽 也不倍高
				}
			}
	   		
			CharSequence t =  (CharSequence)in_String;
			char[] text = new char[t.length()];	//声明一个和所输入字符串同样长度的字符数组
			for (i=0; i<t.length(); i++) {
				text[i] = t.charAt(i);		//把CharSequence中的charAt传入刚声明的字符数组中
			}
			try {
				byte[] buffer = prt_code_buffer;//倍高倍宽;
				mOutputStream.write(buffer);
				mOutputStream.write(new String(text).getBytes("gb2312"));	//把字符数组变成byte型发送
			} catch (IOException e) {
				e.printStackTrace();
			}				
		}
	}
	

	/***********  以下是结账对话框       *********************/
    private Dialog buildCheckDialog(Context context) {
		// TODO Auto-generated method stub
        final AlertDialog.Builder builder =   new AlertDialog.Builder(context);  
        //下面是设置对话框的属性
        builder.setIcon(drawable.other_1);
        builder.setTitle("结账消费管理");  
        LayoutInflater inflater = LayoutInflater.from(Table2.this);
        View view = null ;
        ref_if = false;
        switch (Dispay_widthPixels) {
			case 1024:
		        view = inflater.inflate(R.layout.i800dialog_cai_check, null);			
				break;
			case 800:
		        view = inflater.inflate(R.layout.i800dialog_cai_check, null);			
				break;
			default:
		        view = inflater.inflate(R.layout.i800dialog_cai_check, null);			
				break;
		}
        builder.setView(view);
        builder.setCancelable(false);
 
        
        DAILOG_CHECK_TEXT_TAIHAO		=	(TextView) view.findViewById(id.dialog_check_tx_taihao);
        DAILOG_CHECK_TEXT_DANHAO		=	(TextView) view.findViewById(id.dialog_check_tx_danhao);
    	DAILOG_CHECK_TEXT_KAITAISHIJIAN =	(TextView) view.findViewById(id.dialog_check_tx_kaitaishijian);
    	DAILOG_CHECK_TEXT_RENSHU 		=	(TextView) view.findViewById(id.dialog_check_renshu);
    	DAILOG_CHECK_TEXT_KAITAIREN 	=	(TextView) view.findViewById(id.dialog_check_kaitairen);
    	DAILOG_CHECK_TEXT_XIAOFEI 		=	(TextView) view.findViewById(id.dialog_check_block2_tx_xiaofei);
    	DAILOG_CHECK_TEXT_JIASHOU 		=	(TextView) view.findViewById(id.dialog_check_block2_tx_jiashou);
    	DAILOG_CHECK_TEXT_ZHEKOU 		=	(TextView) view.findViewById(id.dialog_check_block2_tx_zhekou);
    	DAILOG_CHECK_TEXT_ZONGJI 		=	(TextView) view.findViewById(id.dialog_check_block2_tx_zongji);
    	DAILOG_CHECK_TEXT_YINGSHOU 		=	(TextView) view.findViewById(id.dialog_check_block2_tx_yingshou);
    	DAILOG_CHECK_TEXT_XIANSJIN 		=	(TextView) view.findViewById(id.dialog_check_block2_tx_xianjin);
    	DAILOG_CHECK_TEXT_ZHAOLING 		=	(TextView) view.findViewById(id.dialog_check_block2_tx_zhaoling);
    	DAILOG_CHECK_TEXT_KAOHAO 		=	(TextView) view.findViewById(id.dialog_check_kahao);
    	DAILOG_CHECK_TEXT_JIFEN 		=	(TextView) view.findViewById(id.dialog_check_jifen);
    	DAILOG_CHECK_TEXT_KAYUKE 		=	(TextView) view.findViewById(id.dialog_check_yue);
        DAILOG_CHECK_TEXT_LEIXING		=	(TextView) view.findViewById(id.dialog_check_leixing);

        DAILOG_BTN_CHECK_0	=	(Button) view.findViewById(id.dialog_check_btn_control_0);
        DAILOG_BTN_CHECK_1	=	(Button) view.findViewById(id.dialog_check_btn_control_1);
        DAILOG_BTN_CHECK_2	=	(Button) view.findViewById(id.dialog_check_btn_control_2);
        DAILOG_BTN_CHECK_3	=	(Button) view.findViewById(id.dialog_check_btn_control_3);
        DAILOG_BTN_CHECK_4	=	(Button) view.findViewById(id.dialog_check_btn_control_4);
        DAILOG_BTN_CHECK_5	=	(Button) view.findViewById(id.dialog_check_btn_control_5);
        DAILOG_BTN_CHECK_6	=	(Button) view.findViewById(id.dialog_check_btn_control_6);
        DAILOG_BTN_CHECK_7	=	(Button) view.findViewById(id.dialog_check_btn_control_7);
        DAILOG_BTN_CHECK_8	=	(Button) view.findViewById(id.dialog_check_btn_control_8);
        DAILOG_BTN_CHECK_9	=	(Button) view.findViewById(id.dialog_check_btn_control_9);
        DAILOG_BTN_CHECK_CLEAR	=	(Button) view.findViewById(id.dialog_check_btn_control_clear);
        DAILOG_BTN_CHECK_DEL	=	(Button) view.findViewById(id.dialog_check_btn_control_del);

        DAILOG_BTN_CHECK_SK	=	(Button) view.findViewById(id.dialog_check_btn_control_card);
        DAILOG_BTN_CHECK	=	(Button) view.findViewById(id.dialog_check_button_enter_casio);
        DAILOG_BTN_EXIT		=	(Button) view.findViewById(id.dialog_check_button_exit);
       
        get_table_message(Share_Table_Num);
    	DAILOG_CHECK_TEXT_TAIHAO.setText(Share_Table_Num);
    	String	Sell_number = get_table_sellnum(Share_Table_Num);	//该桌的销售单号
    	DAILOG_CHECK_TEXT_DANHAO.setText( Sell_number );
    	
    	//根据销售单号查询销售信息 ，菜的总价！人数！应收！加收！等等之类的
		try {
			String[] sell_number = {Sell_number};
			Cursor  cursor = db.rawQuery("select * from lfcy_base_sellinf where cSellNo= ?", sell_number);
			float	Total_All = 0;
			while(cursor.moveToNext()) 
			{
				String Sprice = cursor.getString(cursor.getColumnIndex("fDishPrice"));
			    float i = Float.parseFloat(Sprice);

			    Total_All = Total_All + i;
			}		
			DAILOG_CHECK_TEXT_XIAOFEI.setText(""+Total_All);			
		} catch (Exception e) {
			// TODO: handle exception
		}
    	
    	
    	//操作员
    	DAILOG_CHECK_TEXT_KAITAIREN.setText(UserCode);

	    float tatal = Float.parseFloat(DAILOG_CHECK_TEXT_XIAOFEI.getText().toString());
	
	    float jaishou = 0;	
	    
    	DAILOG_CHECK_TEXT_ZONGJI.setText(""+(tatal+jaishou));
    	DAILOG_CHECK_TEXT_YINGSHOU.setText(""+(tatal+jaishou));

    	SerialPort mSerialPort = null;		//串口设备描述
   		String TTY_DEV = "/dev/ttymxc1";

		try {
			mSerialPort = new SerialPort(new File(TTY_DEV), 2400, 0);
		} catch (SecurityException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}	
		
		try {
			mOutputStream = mSerialPort.getOutputStream();	
			
		} catch (Exception e) {
			// TODO: handle exception
		}

		String contenr = DAILOG_CHECK_TEXT_YINGSHOU.getText().toString();
		try {
			Sent_Customer_Clear(contenr);			
		} catch (Exception e) {
			// TODO: handle exception
		}	
//    	DAILOG_CHECK_TEXT_KAOHAO.setText(Sell_Num);
//    	DAILOG_CHECK_TEXT_JIFEN.setText(Sell_Num);
//    	DAILOG_CHECK_TEXT_KAYUKE.setText(Sell_Num);
        
		
		DAILOG_BTN_CHECK_SK.setOnClickListener(new OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
		   		removeDialog(DIALOG_JIEZHANG);  //关闭对话框 
//		        init_grid(1);
		        Refresh_State();
		   	}
	    });
		
		DAILOG_BTN_EXIT.setOnClickListener(new OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
		   		removeDialog(DIALOG_JIEZHANG);  //关闭对话框 
//		        init_grid(1);
		        Refresh_State();	
		        ref_if = true;
		        System.out.println("DAILOG_BTN_EXIT");
		    }
	    });
		
		DAILOG_BTN_CHECK.setOnClickListener(new OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
		   		try {
//				    Integer intObj = new Integer(DAILOG_CHECK_TEXT_YINGSHOU.getText().toString());
//				    int tatal = intObj.intValue();	
				    float tatal = Float.parseFloat(DAILOG_CHECK_TEXT_YINGSHOU.getText().toString());

//				    intObj = new Integer(DAILOG_CHECK_TEXT_XIANSJIN.getText().toString());
//				    int xianjin = intObj.intValue();	
				    float xianjin = Float.parseFloat(DAILOG_CHECK_TEXT_XIANSJIN.getText().toString());
				    
				    if(xianjin >= tatal )
				    {	
				    	DAILOG_CHECK_TEXT_ZHAOLING.setText(""+( xianjin - tatal));
				   		ContentValues cv = new ContentValues();
					   	//存储修改的数据
					   	cv.put("iTableState" ,3);
					   	cv.put("iTable_Person","");
					   	cv.put("iTabletime","");
					   	String[] contion = {Share_Table_Num}; 
				   		try {
						   	//更新数据
						   	db.update("lfcy_base_tableinf",cv,"iTableNumber = ? ",contion);
						} catch (Exception e) {
							// TODO: handle exception
						}
						
						/**
						 * 根据销售单号，桌号，人数，操作员，销售金额，结账时间，生成结账数据
						 **/
						//查找店号，机号，操作员
			    		Cursor  cursor = db.rawQuery("select * from lfcy_base_posinf ", null);
			    		cursor.moveToFirst();
			    		String iPosMachineNum = cursor.getString(1).toString();	//机器号
			    		String iPosShopNum = cursor.getString(2).toString();	//门店号
			    		
						//获取结账日期和时间
			       		final Calendar c = 
			       			Calendar.getInstance();
			       			        mYear	= c.get(Calendar.YEAR); 	//获取当前年份
			       			        mMonth 	= c.get(Calendar.MONTH)+1;	//获取当前月份
			       			        mDay 	= c.get(Calendar.DAY_OF_MONTH);//获取当前月份的日期号码
			       			        mHour 	= c.get(Calendar.HOUR_OF_DAY);//获取当前的小时数
			       			        mMinute = c.get(Calendar.MINUTE);	//获取当前的分钟数		   		
			       							
						//根据店号机号结账日期和流水生成一条结账单号
						String	Check_Code	=	iPosShopNum+iPosMachineNum+mYear+mMonth+mDay+mHour+mMinute;
			       			        
						//增加一条结账数据
     					//结账时间//操作员编码//门店号//机器号//桌台号//结账单号//销售单号（利用开台时间）
						//实际消费金额//服务费及加收金额//打折及直减金额//最终应收交易金额
						//最终实收交易金额  //找零金额//桌台容纳人数
						insert_CheckData(db ,
								mYear+"-"+mMonth+"-"+mDay+" "+mHour+":"+mMinute,  
								UserCode , 
								iPosShopNum ,
								iPosMachineNum , 
								DAILOG_CHECK_TEXT_TAIHAO.getText().toString() , 
								Check_Code  ,
								DAILOG_CHECK_TEXT_DANHAO.getText().toString() ,
								DAILOG_CHECK_TEXT_XIAOFEI.getText().toString(),
								DAILOG_CHECK_TEXT_JIASHOU.getText().toString(),
								DAILOG_CHECK_TEXT_ZHEKOU.getText().toString(),
								DAILOG_CHECK_TEXT_YINGSHOU.getText().toString(),
								DAILOG_CHECK_TEXT_XIANSJIN.getText().toString(),
								DAILOG_CHECK_TEXT_ZHAOLING.getText().toString(),
								DAILOG_CHECK_TEXT_RENSHU.getText().toString()								
							);

				   		/***/
				   		CheckTitle = "     欢迎光临“8090自助餐厅”";
				   		CheckTableNum = DAILOG_CHECK_TEXT_TAIHAO.getText().toString();
				   		CheckNum = Check_Code;
				   		CheckContent = "编号  菜品名称   数量   价格";
				   		CheckDanhao = DAILOG_CHECK_TEXT_DANHAO.getText().toString();
				   		CheckXiaoFeiZongJia = DAILOG_CHECK_TEXT_XIAOFEI.getText().toString();
				   		CheckJiaShou = DAILOG_CHECK_TEXT_JIASHOU.getText().toString();
				   		CheckYingShou = DAILOG_CHECK_TEXT_YINGSHOU.getText().toString();
				   		CheckXianJinShiSHou = DAILOG_CHECK_TEXT_XIANSJIN.getText().toString();
				   		CheckZhaoLing = DAILOG_CHECK_TEXT_ZHAOLING.getText().toString();
				   		CheckUser = UserCode;
				   		CheckDateTime = mYear+"-"+mMonth+"-"+ mDay +" "+mHour+":"+mMinute;
				   		/***/
				   		
						//启动一条线程！负责获取打印内容，打印格式，最终打印出来
				   		try {
					   		Save_SharePreference();					
				   		} catch (Exception e) {
							// TODO: handle exception
				   			Toast.makeText(Table2.this, "保存失败，请检查数据是否设置正确", Toast.LENGTH_SHORT).show();
				   		}	

				    }
				    else
				    	Toast.makeText(Table2.this, "请重新输入现金", Toast.LENGTH_SHORT).show();					
				} catch (Exception e) {
			    	Toast.makeText(Table2.this, "请输入现金后,再按结账按钮", Toast.LENGTH_SHORT).show();					
				}
				
				new Handler().postDelayed(new Runnable(){   
				    public void run() {   
				    //execute the task   
				    	Toast.makeText(Table2.this, "       找零"+ DAILOG_CHECK_TEXT_ZHAOLING.getText().toString()+"元       ", Toast.LENGTH_LONG).show();					
				   		removeDialog(DIALOG_JIEZHANG);  //关闭对话框 
//				        init_grid(1);
				        Refresh_State();
				        ref_if = true;
				    }   
				 }, 3000);  
				
		    	
		   	}
	    });
		DAILOG_BTN_CHECK_1.setOnClickListener(new OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
		   		String	num	=	DAILOG_CHECK_TEXT_XIANSJIN.getText().toString();
		   		DAILOG_CHECK_TEXT_XIANSJIN.setText(num +  1	);		   	
		   	}
	    });
		DAILOG_BTN_CHECK_2.setOnClickListener(new OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
		   		String	num	=	DAILOG_CHECK_TEXT_XIANSJIN.getText().toString();
		   		DAILOG_CHECK_TEXT_XIANSJIN.setText(num +  2	);		   	
		   	}
	    });
		DAILOG_BTN_CHECK_3.setOnClickListener(new OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
		   		String	num	=	DAILOG_CHECK_TEXT_XIANSJIN.getText().toString();
		   		DAILOG_CHECK_TEXT_XIANSJIN.setText(num + 3	);		   	
		   	}
	    });		
		DAILOG_BTN_CHECK_4.setOnClickListener(new OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
		   		String	num	=	DAILOG_CHECK_TEXT_XIANSJIN.getText().toString();
		   		DAILOG_CHECK_TEXT_XIANSJIN.setText(num + 4	);		   	
		   	}
	    });		
		DAILOG_BTN_CHECK_5.setOnClickListener(new OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
		   		String	num	=	DAILOG_CHECK_TEXT_XIANSJIN.getText().toString();
		   		DAILOG_CHECK_TEXT_XIANSJIN.setText(num + 5	);		   	
		   	}
	    });		
		DAILOG_BTN_CHECK_6.setOnClickListener(new OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
		   		String	num	=	DAILOG_CHECK_TEXT_XIANSJIN.getText().toString();
		   		DAILOG_CHECK_TEXT_XIANSJIN.setText(num +  6);		   	
		   	}
	    });		
		DAILOG_BTN_CHECK_7.setOnClickListener(new OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
		   		String	num	=	DAILOG_CHECK_TEXT_XIANSJIN.getText().toString();
		   		DAILOG_CHECK_TEXT_XIANSJIN.setText(num + 7	);		   	
		   	}
	    });		
		DAILOG_BTN_CHECK_8.setOnClickListener(new OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
		   		String	num	=	DAILOG_CHECK_TEXT_XIANSJIN.getText().toString();
		   		DAILOG_CHECK_TEXT_XIANSJIN.setText(num +  8	);		   	
		   	}
	    });		
		DAILOG_BTN_CHECK_9.setOnClickListener(new OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
		   		String	num	=	DAILOG_CHECK_TEXT_XIANSJIN.getText().toString();
		   		DAILOG_CHECK_TEXT_XIANSJIN.setText(num +  9	);		   	
		   	}
	    });	
		DAILOG_BTN_CHECK_0.setOnClickListener(new OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
		   		String	num	=	DAILOG_CHECK_TEXT_XIANSJIN.getText().toString();
		   		DAILOG_CHECK_TEXT_XIANSJIN.setText(num +  0	);		   	
		   	}
	    });			
		DAILOG_BTN_CHECK_CLEAR.setOnClickListener(new OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
		   		DAILOG_CHECK_TEXT_XIANSJIN.setText("");		   	
		   	}
	    });			
		DAILOG_BTN_CHECK_DEL.setOnClickListener(new OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
		   		try {
			   		String	num	=	DAILOG_CHECK_TEXT_XIANSJIN.getText().toString();
			   		String	str =	num.substring(0,num.length()-1);
			   		DAILOG_CHECK_TEXT_XIANSJIN.setText( str	);						
				} catch (Exception e) {
					// TODO: handle exception
					Toast.makeText(Table2.this, "请输入金额",	Toast.LENGTH_SHORT ).show();
				}
	   	
		   	}
	    });			
		
		return builder.create();  
    } 
	
    protected void insert_CheckData(SQLiteDatabase db, 
    		String dtCheckDate,	//结账日期
			String cUserCode, 	//操作员编码
			String iPosShopNum, //店号
			String iPosMachineNum,	//机号
			String iTableNumber, //结账的桌号
			String cPayNo, //付款单号
			String cSellNo,	//销售单号（利用开台时间）
			String fSaleSum,	//实际消费金额
			String fSvrSum,//服务费及加收金额
			String fReduceSum, //打折及直减金额
			String fTradeSum, //最终应收交易金额
			String fTradeEndSum,//最终实收交易金额
			String fPayBackSum, //找零金额
			String iTable_Person) //桌台容纳人数
    {
			
		// TODO Auto-generated method stub
		db.execSQL("insert into lfcy_base_tablecheckinf values(null,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", 
				new String[]{ 
					dtCheckDate,		//结账时间
					cUserCode ,			//操作员编码
					iPosShopNum , 		//门店号
					iPosMachineNum , 	//机器号
					iTableNumber  ,		//桌台号
					cPayNo , 			//结账单号
					cSellNo,			//销售单号（利用开台时间）
					fSaleSum,			//实际消费金额
					fSvrSum,			//服务费及加收金额
					fReduceSum,			//打折及直减金额
					fTradeSum,			//最终应收交易金额
					fTradeEndSum,		//最终实收交易金额
					fPayBackSum,		//找零金额
					iTable_Person		//桌台容纳人数
		 });
	}

	//根据桌号查询桌台信息     桌的状态，桌的属性（大厅 ，包厢 ，卡座）
	private void get_table_message(String table_Num2) {
		// TODO Auto-generated method stub
		String[] Contind	= {table_Num2};
		try {
			//根据桌号查询桌台消费信息
    		Cursor  cursor = db.rawQuery("select * from lfcy_base_tableinf where iTableNumber = ?", Contind);
    		cursor.moveToFirst();
    		int    TABLE_STYLE = cursor.getInt(2);
    		String iTabletime = cursor.getString(5).toString();
    		String iTable_Person = cursor.getString(7).toString();	
    		
    	    Integer intObj = new Integer(iTable_Person);
    	    int person = intObj.intValue();	
    		if(TABLE_STYLE == 1)
    		{	
    			DAILOG_CHECK_TEXT_LEIXING.setText("大厅");
    			DAILOG_CHECK_TEXT_JIASHOU.setText(""+(person*2));
    		}
    		if(TABLE_STYLE == 2)
    		{	
    			DAILOG_CHECK_TEXT_LEIXING.setText("包厢");
    			DAILOG_CHECK_TEXT_JIASHOU.setText(""+person*2);       	
    		}
    		if(TABLE_STYLE == 3)
    		{	
    			DAILOG_CHECK_TEXT_LEIXING.setText("卡座");
    			DAILOG_CHECK_TEXT_JIASHOU.setText(""+person*5);
    		}
    		DAILOG_CHECK_TEXT_KAITAISHIJIAN.setText(iTabletime);
        	DAILOG_CHECK_TEXT_RENSHU.setText(iTable_Person);

		} catch (Exception e) {
			// TODO: handle exception
		}
		
	}
	/***********  以上是结账对话框       *********************/
	
	
	/***      初始一个对话框！ 命名为buildDialog      ***/
    private Dialog buildDialog(Context context) {
		// TODO Auto-generated method stub
        final AlertDialog.Builder builder =   new AlertDialog.Builder(context);  
        //下面是设置对话框的属性
        builder.setIcon(drawable.other_1);
        builder.setTitle("桌台操作");  
        LayoutInflater inflater = LayoutInflater.from(Table2.this);
        View view = null ;
        ref_if = false;

        switch (Dispay_widthPixels) {
			case 1024:
//		        view = inflater.inflate(R.layout.dialog_table_control, null);			
		        view = inflater.inflate(R.layout.i800dialog_table_control, null);			
				break;
			case 800:
		        view = inflater.inflate(R.layout.i800dialog_table_control, null);			
				break;
			default:
		        view = inflater.inflate(R.layout.i800dialog_table_control, null);			
				break;
		}
        builder.setView(view);
        builder.setCancelable(false);
        
        
		DAILOG_BTN_KAITAI 	= (Button) view.findViewById(id.diglog_table_kaitai);
		DAILOG_BTN_DIANCAI 	= (Button) view.findViewById(id.diglog_table_diancai);
		DAILOG_BTN_JIACAI 	= (Button) view.findViewById(id.diglog_table_jiacai);
		DAILOG_BTN_CHACAI 	= (Button) view.findViewById(id.diglog_table_chacai);
		DAILOG_BTN_JIEZHANG = (Button) view.findViewById(id.diglog_table_jiezhang);
		DAILOG_BTN_XIAOTAI 	= (Button) view.findViewById(id.diglog_table_xiaotai);
		DAILOG_BTN_ZHUANTAI	= (Button) view.findViewById(id.diglog_table_zhuantai);
		DAILOG_BTN_CUICAI	= (Button) view.findViewById(id.diglog_table_cuicai);
		
		DAILOG_TEXT_TABLE_NUM = (TextView) view.findViewById(id.diglog_table_number);
		DAILOG_TEXT_TABLE_SELLNUM = (TextView) view.findViewById(id.diglog_table_sellnumber);

		DAILOG_TEXT_TABLE_NUM.setText(Share_Table_Num );
		DAILOG_TEXT_TABLE_SELLNUM.setText(get_table_sellnum(Share_Table_Num));
		
		set_table_button_state( Share_Table_State);	//根据所选桌台的状态来设置按钮的是否能被触发
        
		DAILOG_BTN_KAITAI.setOnClickListener(new OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
		   		//获取桌台号和即时时间     生成销售单号
		   		
		   		//设置用餐人数
		   		
		   		//开台
		   		
		   		removeDialog(DIALOG_FIND);  //关闭对话框 
		   	}

	    });

		DAILOG_BTN_DIANCAI.setOnClickListener(new OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
		   	    Bundle bundle = new Bundle();
		   	    //保存输入的信息
		   	    bundle.putString("table_number", Share_Table_Num);
		   	    bundle.putString("sell_number", get_table_sellnum(Share_Table_Num));
		   	    bundle.putString("UserCode", UserCode);
	    		Intent intent_page_new = new Intent();
    			intent_page_new.setClass(Table2.this, Cai.class);	    			
    			intent_page_new.putExtras(bundle);
	    		startActivity(intent_page_new);	
				overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
		   		removeDialog(DIALOG_FIND);  //关闭对话框 
		   	}

	    });
		
		DAILOG_BTN_JIACAI.setOnClickListener(new OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
		   	    Bundle bundle = new Bundle();
		   	    //保存输入的信息
		   	    bundle.putString("table_number", Share_Table_Num);
		   	    bundle.putString("sell_number", get_table_sellnum(Share_Table_Num));
		   	    bundle.putString("UserCode", UserCode);
	    		Intent intent_page_new = new Intent();
    			intent_page_new.setClass(Table2.this, Cai.class);	    			
    			intent_page_new.putExtras(bundle);
	    		startActivity(intent_page_new);	
				overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
		   		removeDialog(DIALOG_FIND);  //关闭对话框 
		   	}

	    });
		
		DAILOG_BTN_CHACAI.setOnClickListener(new OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
		   	    Bundle bundle = new Bundle();
		   	    //保存输入的信息
		   	    bundle.putString("table_number", Share_Table_Num);
		   	    bundle.putString("sell_number", get_table_sellnum(Share_Table_Num));
		   	    bundle.putString("UserCode", UserCode);
	    		Intent intent_page_new = new Intent();
    			intent_page_new.setClass(Table2.this, Cai.class);	    			
    			intent_page_new.putExtras(bundle);
	    		startActivity(intent_page_new);	
				overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
		   		removeDialog(DIALOG_FIND);  //关闭对话框 
		   	}
	    });		

		DAILOG_BTN_JIEZHANG.setOnClickListener(new OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
		   		//结账
		   		removeDialog(DIALOG_FIND);  //关闭对话框 
                showDialog(DIALOG_JIEZHANG);
		   	}

	    });		
		
		DAILOG_BTN_XIAOTAI.setOnClickListener(new OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
		   		//消台
		   		ContentValues cv = new ContentValues();
			   	//存储修改的数据
			   	cv.put("iTableState" ,1);
			   	cv.put("iTable_Person","");
			   	cv.put("iTabletime","");
			   	String[] contion = {Share_Table_Num}; 
		   		try {
				   	//更新数据
				   	db.update("lfcy_base_tableinf",cv,"iTableNumber = ? ",contion);
				} catch (Exception e) {
					// TODO: handle exception
				}
//		        init_grid(1);
		        Refresh_State();		        
		   		removeDialog(DIALOG_FIND);  //关闭对话框 			
		        ref_if = true;

		   	}
	    });		

		DAILOG_BTN_ZHUANTAI.setOnClickListener(new OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
		   		//转台
		   		//获取转台前的必备数据
		   		//启动点菜界面 并传入数据
		   	    Bundle bundle = new Bundle();
		   	    //保存输入的信息
		   	    bundle.putString("table_number", Share_Table_Num);
		   	    bundle.putString("sell_number", get_table_sellnum(Share_Table_Num));
		   		//启动转台界面		   		
				Intent intent_page_new = new Intent();
				intent_page_new.setClass(Table2.this, Table_ZhuanTai.class);			
    			intent_page_new.putExtras(bundle);
				startActivity(intent_page_new);	
				overridePendingTransition(R.anim.zoomin, R.anim.zoomout);	   		
		   		removeDialog(DIALOG_FIND);  //关闭对话框 
		   	}

	    });		

		DAILOG_BTN_CUICAI.setOnClickListener(new OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
		   		//返回
				overridePendingTransition(R.anim.in_from_top, R.anim.out_to_bottom);	   				   		
		   		removeDialog(DIALOG_FIND);  //关闭对话框 
				overridePendingTransition(R.anim.zoomin, R.anim.zoomout);	   		
		        ref_if = true;
		   	}
	    });
		
        return builder.create();  
    } 
    
    private	String get_table_sellnum(String table_num)
    {
    	String table_sellnum = null;
    	String[]	Stable_num = {table_num};
    	try {
    		Cursor  cursor = db.rawQuery("select * from lfcy_base_opentableinf where iTableNumber = ?", Stable_num);
    		cursor.moveToLast();
    		table_sellnum = cursor.getString(1).toString();
		} catch (Exception e) {
			// TODO: handle exception
		}
		return table_sellnum;
    }
    
	private void set_table_button_state(String share_Table_State2) {
		// TODO Auto-generated method stub
		DAILOG_BTN_XIAOTAI.setVisibility(View.VISIBLE);
		DAILOG_BTN_JIACAI.setVisibility(View.VISIBLE);
		DAILOG_BTN_JIEZHANG.setVisibility(View.VISIBLE);
		DAILOG_BTN_ZHUANTAI.setVisibility(View.VISIBLE);

		Integer intObj = new Integer(share_Table_State2);
	    int i = intObj.intValue();	
		switch (i) {	//空闲的情况
		case 1:
			DAILOG_BTN_KAITAI.setEnabled(true);
			DAILOG_BTN_KAITAI.setTextColor(Color.rgb(255,255,255));
			DAILOG_BTN_DIANCAI.setEnabled(false);
			DAILOG_BTN_DIANCAI.setTextColor(R.color.lightgray);
			DAILOG_BTN_JIACAI.setEnabled(false);
			DAILOG_BTN_JIACAI.setTextColor(R.color.lightgray);
			DAILOG_BTN_CHACAI.setEnabled(false);
			DAILOG_BTN_CHACAI.setTextColor(R.color.lightgray);
			DAILOG_BTN_JIEZHANG.setEnabled(false);
			DAILOG_BTN_JIEZHANG.setTextColor(R.color.lightgray);
			DAILOG_BTN_XIAOTAI.setEnabled(false);			
			DAILOG_BTN_XIAOTAI.setTextColor(R.color.lightgray);
			DAILOG_BTN_ZHUANTAI.setEnabled(false);			
			DAILOG_BTN_ZHUANTAI.setTextColor(R.color.lightgray);
			break;
		case 2: 	//已点的情况
			DAILOG_BTN_KAITAI.setEnabled(false);
			DAILOG_BTN_KAITAI.setTextColor(R.color.lightgray);
			DAILOG_BTN_DIANCAI.setEnabled(false);
			DAILOG_BTN_DIANCAI.setTextColor(R.color.lightgray);
			DAILOG_BTN_JIACAI.setEnabled(true);
			DAILOG_BTN_JIACAI.setTextColor(Color.rgb(255,255,255));
			DAILOG_BTN_CHACAI.setEnabled(true);
			DAILOG_BTN_CHACAI.setTextColor(Color.rgb(255,255,255));
			DAILOG_BTN_JIEZHANG.setEnabled(true);
			DAILOG_BTN_JIEZHANG.setTextColor(Color.rgb(255,255,255));
			DAILOG_BTN_XIAOTAI.setEnabled(false);			
			DAILOG_BTN_XIAOTAI.setTextColor(R.color.lightgray);
			DAILOG_BTN_ZHUANTAI.setEnabled(true);			
			DAILOG_BTN_ZHUANTAI.setTextColor(Color.rgb(255,255,255));	
			DAILOG_BTN_XIAOTAI.setVisibility(View.GONE);
			break;
		case 3:		//结账但未清台的情况
			DAILOG_BTN_KAITAI.setEnabled(false);
			DAILOG_BTN_KAITAI.setTextColor(R.color.lightgray);
			DAILOG_BTN_DIANCAI.setEnabled(false);
			DAILOG_BTN_DIANCAI.setTextColor(R.color.lightgray);
			DAILOG_BTN_JIACAI.setEnabled(false);
			DAILOG_BTN_JIACAI.setTextColor(R.color.lightgray);
			DAILOG_BTN_CHACAI.setEnabled(false);
			DAILOG_BTN_CHACAI.setTextColor(R.color.lightgray);
			DAILOG_BTN_JIEZHANG.setEnabled(false);
			DAILOG_BTN_JIEZHANG.setTextColor(R.color.lightgray);
			DAILOG_BTN_XIAOTAI.setEnabled(true);			
			DAILOG_BTN_XIAOTAI.setTextColor(Color.rgb(255,255,255));
			DAILOG_BTN_ZHUANTAI.setEnabled(false);			
			DAILOG_BTN_ZHUANTAI.setTextColor(R.color.lightgray);	
			DAILOG_BTN_JIACAI.setVisibility(View.GONE);
			DAILOG_BTN_JIEZHANG.setVisibility(View.GONE);
			DAILOG_BTN_ZHUANTAI.setVisibility(View.GONE);
			break;			
		default:
			break;
		}

	}

	@Override 
    protected Dialog onCreateDialog(int id) {  
        // TODO Auto-generated method stub  
        if(id==101){  
        	return this.buildDialog(Table2.this);  
        }
        if(id==102){  
        	return this.buildaDialog(Table2.this);  
        }
        if(id==103){  
        	return this.buildCheckDialog(Table2.this);  
        }
        else{  
            return null;  
        }  
    } 

    @Override 
    protected void onPrepareDialog(int id, Dialog dialog) {  
        // TODO Auto-generated method stub  
        super.onPrepareDialog(DIALOG_FIND, dialog);  
    } 
    /***      以上是初始一个对话框！       ***/	
    
    
    
    
	
	/***      初始一个对话框！ 命名为buildDialog      ***/
	int mYear,mMonth,mDay,mHour,mMinute;
	String mmMonth,mmDay,mmHour,mmMinute;

    private Dialog buildaDialog(Context context) {
		// TODO Auto-generated method stub
        final AlertDialog.Builder builder =   new AlertDialog.Builder(context);  
        //下面是设置对话框的属性
        builder.setIcon(drawable.other_1);
        builder.setTitle("开台操作");  
        LayoutInflater inflater = LayoutInflater.from(Table2.this);
        View view = null ;
        ref_if = false;

        switch (Dispay_widthPixels) {
			case 1024:
//		        view = inflater.inflate(R.layout.dialog_table_control, null);			
		        view = inflater.inflate(R.layout.dailog_table_personnumber, null);			
				break;
			case 800:
		        view = inflater.inflate(R.layout.dailog_table_personnumber, null);			
				break;
			default:
		        view = inflater.inflate(R.layout.dailog_table_personnumber, null);			
				break;
		}
        builder.setView(view);
        builder.setCancelable(false);        

        DAILOG_BTN_PER_0		= (Button)  view.findViewById(id.table_btn_0);
        DAILOG_BTN_PER_1		= (Button)  view.findViewById(id.table_btn_1);
        DAILOG_BTN_PER_2		= (Button)  view.findViewById(id.table_btn_2);
        DAILOG_BTN_PER_3		= (Button)  view.findViewById(id.table_btn_3);
        DAILOG_BTN_PER_4		= (Button)  view.findViewById(id.table_btn_4);
        DAILOG_BTN_PER_5		= (Button)  view.findViewById(id.table_btn_5);
        DAILOG_BTN_PER_6		= (Button)  view.findViewById(id.table_btn_6);
        DAILOG_BTN_PER_7		= (Button)  view.findViewById(id.table_btn_7);
        DAILOG_BTN_PER_8		= (Button)  view.findViewById(id.table_btn_8);
        DAILOG_BTN_PER_9		= (Button)  view.findViewById(id.table_btn_9);
        DAILOG_BTN_PER_DEL		= (Button)  view.findViewById(id.table_btn_del);
        
		DAILOG_BTN_KAITAI2 		= (Button) view.findViewById(id.dialog_num_kaitai);
		DAILOG_BTN_DIANCAI2 	= (Button) view.findViewById(id.dialog_num_diancai);
		DAILOG_BTN_CANCEL 		= (Button) view.findViewById(id.dialog_num_cancel);
		DAILOG_TEXT_PERSON_NUM	=	(TextView) view.findViewById(id.dialog_person_num);
		DAILOG_TEXT_DANHAO		=	(TextView) view.findViewById(id.dialog_text_danhao);

   		//获取桌台号和即时时间    
   		final Calendar c = 
   			Calendar.getInstance();
   			        mYear	= c.get(Calendar.YEAR); 	//获取当前年份
   			        mMonth 	= c.get(Calendar.MONTH)+1;	//获取当前月份
   			        mDay 	= c.get(Calendar.DAY_OF_MONTH);//获取当前月份的日期号码
   			        mHour 	= c.get(Calendar.HOUR_OF_DAY);//获取当前的小时数
   			        mMinute = c.get(Calendar.MINUTE);	//获取当前的分钟数		   		
   	
   		if(mMonth<10)
   		{	
   			mmMonth="0"+mMonth;
   		}
   		else
   			mmMonth=""+mMonth;
   			
   		
   		if(mDay<10)
   		{	
   			mmDay="0"+mDay;
   		} 
   		else
   			mmDay=""+mDay;
   		
   		
   		if(mHour<10)
   		{	
   			mmHour="0"+mHour;
   		}   		
   		else
   			mmHour=""+mHour;
   		
   		
   		if(mMinute<10)
   		{	
   			mmMinute="0"+mMinute;
   		}   		
   		else
   			mmMinute=""+mMinute;
   		
   		final String Sell_Number	=	Share_Table_Num+mYear+mmMonth+mmDay+mmHour+mmMinute;
		DAILOG_TEXT_DANHAO.setText(Sell_Number);
		
		DAILOG_BTN_PER_0.setOnClickListener(new OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
			   	String	per_num	=	DAILOG_TEXT_PERSON_NUM.getText().toString();
		   		DAILOG_TEXT_PERSON_NUM.setText(per_num + 0	);	
		   	}
	    });			
		DAILOG_BTN_PER_1.setOnClickListener(new OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
			   	String	per_num	=	DAILOG_TEXT_PERSON_NUM.getText().toString();
		   		DAILOG_TEXT_PERSON_NUM.setText(per_num + 1	);	
		   	}
	    });	
		DAILOG_BTN_PER_2.setOnClickListener(new OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
			   	String	per_num	=	DAILOG_TEXT_PERSON_NUM.getText().toString();
		   		DAILOG_TEXT_PERSON_NUM.setText(per_num + 2	);	
		   	}
	    });			
		DAILOG_BTN_PER_3.setOnClickListener(new OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
			   	String	per_num	=	DAILOG_TEXT_PERSON_NUM.getText().toString();
		   		DAILOG_TEXT_PERSON_NUM.setText(per_num + 3	);	
		   	}
	    });	
		DAILOG_BTN_PER_4.setOnClickListener(new OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
			   	String	per_num	=	DAILOG_TEXT_PERSON_NUM.getText().toString();
		   		DAILOG_TEXT_PERSON_NUM.setText(per_num + 4	);	
		   	}
	    });			
		DAILOG_BTN_PER_5.setOnClickListener(new OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
			   	String	per_num	=	DAILOG_TEXT_PERSON_NUM.getText().toString();
		   		DAILOG_TEXT_PERSON_NUM.setText(per_num + 5	);	
		   	}
	    });			
		DAILOG_BTN_PER_6.setOnClickListener(new OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
			   	String	per_num	=	DAILOG_TEXT_PERSON_NUM.getText().toString();
		   		DAILOG_TEXT_PERSON_NUM.setText(per_num + 6	);	
		   	}
	    });			
		DAILOG_BTN_PER_7.setOnClickListener(new OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
			   	String	per_num	=	DAILOG_TEXT_PERSON_NUM.getText().toString();
		   		DAILOG_TEXT_PERSON_NUM.setText(per_num + 7	);	
		   	}
	    });			
		DAILOG_BTN_PER_8.setOnClickListener(new OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
			   	String	per_num	=	DAILOG_TEXT_PERSON_NUM.getText().toString();
		   		DAILOG_TEXT_PERSON_NUM.setText(per_num + 8	);	
		   	}
	    });			
		DAILOG_BTN_PER_9.setOnClickListener(new OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
			   	String	per_num	=	DAILOG_TEXT_PERSON_NUM.getText().toString();
		   		DAILOG_TEXT_PERSON_NUM.setText(per_num + 9	);	
		   	}
	    });			
		DAILOG_BTN_PER_DEL.setOnClickListener(new OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
		   		try {
			   		String str = null;
			   		String per_num =  DAILOG_TEXT_PERSON_NUM.getText().toString();
		   			str=per_num.substring(0,per_num.length()-1);
		   			DAILOG_TEXT_PERSON_NUM.setText(str);						
				} catch (Exception e) {
					// TODO: handle exception
				}
		   	}
	    });				

		
		DAILOG_BTN_KAITAI2.setOnClickListener(new OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
		   		//设置用餐人数
		   		String person_num	=	DAILOG_TEXT_PERSON_NUM.getText().toString();
		   		if(person_num.equals("") || person_num == null  || person_num.equals("0"))
		   		{//会抛出异常
		   			Toast.makeText(Table2.this, "开台人数不能为空", Toast.LENGTH_LONG).show();
		   		}
		   		else
		   		{	
			   		// 根据桌台号 和 日期合并  生成销售单号
	//		   		String Sell_Number	=	person_num+mYear+mMonth+mDay+mHour+mMinute;
			   		//开台
			   		ContentValues cv = new ContentValues();
				   	//存储修改的数据
				   	cv.put("iTableState" ,2);
				   	cv.put("iTable_Person",person_num);
				   	cv.put("iTabletime",mHour+":"+mMinute);
				   	String[] contion = {Share_Table_Num}; 
			   		try {
					   	//更新数据
					   	db.update("lfcy_base_tableinf",cv,"iTableNumber = ? ",contion);
					} catch (Exception e) {
						// TODO: handle exception
					}
			   		try {
					   	//更新数据
					   	db.execSQL("insert into lfcy_base_opentableinf values(?,?)", 
								new String[]{
					   			Share_Table_Num , Sell_Number});
					} catch (Exception e) {
						// TODO: handle exception
					}
					
//			        init_grid(1);
			        Refresh_State();
			   		removeDialog(DIALOG_KAITAI);  //关闭对话框 
			        ref_if = true;
		   		}
		   	}
	    });

		DAILOG_BTN_DIANCAI2.setOnClickListener(new OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
		   		//设置用餐人数
		   		String person_num	=	DAILOG_TEXT_PERSON_NUM.getText().toString();
		   		if(person_num.equals("") || person_num == null || person_num.equals("0")){//会抛出异常
		   			Toast.makeText(Table2.this, "开台人数不能为空", Toast.LENGTH_LONG).show();
		   		}
		   		else
		   		{
			   		// 根据桌台号 和 日期合并  生成销售单号  	//开台
			   		ContentValues cv = new ContentValues();
				   	//存储修改的数据
				   	cv.put("iTableState" ,2);
				   	cv.put("iTable_Person",person_num);
				   	cv.put("iTabletime",mHour+":"+mMinute);
				   	String[] contion = {Share_Table_Num}; 
			   		try {
					   	//更新数据
					   	db.update("lfcy_base_tableinf",cv,"iTableNumber = ? ",contion);
					} catch (Exception e) {
						// TODO: handle exception
					}
			   		try {
					   	//更新数据
					   	db.execSQL("insert into lfcy_base_opentableinf values(?,?)", 
								new String[]{
					   			Share_Table_Num , Sell_Number});
					} catch (Exception e) {
						// TODO: handle exception
					}
//			        init_grid(1);
			        Refresh_State();		        
			   		removeDialog(DIALOG_KAITAI);  //关闭对话框 
	
			   		//启动点菜界面 并传入数据
			   	    Bundle bundle = new Bundle();
			   	    //保存输入的信息
			   	    bundle.putString("table_number", Share_Table_Num);
			   	    bundle.putString("sell_number", get_table_sellnum(Share_Table_Num));
			   	    bundle.putString("UserCode", UserCode);
		    		Intent intent_page_new = new Intent();
	    			intent_page_new.setClass(Table2.this, Cai.class);	    			
	    			intent_page_new.putExtras(bundle);
		    		startActivity(intent_page_new);	
					overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
		   		}
		   	}
	    });
		
		DAILOG_BTN_CANCEL.setOnClickListener(new OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
		   		removeDialog(DIALOG_KAITAI);  //关闭对话框 
		        ref_if = true;
		   	}
	    });		

        return builder.create();  
    } 
 
    /***      以上是初始一个对话框！       ***/	
	//发送客显显示
  
    
	private void Sent_Customer_Clear(String word) {
		// TODO Auto-generated method stub
   		byte[] cancel_to_normal = {0x1b, 0x51, 0x41 };//清除客显
   		send_customer  (cancel_to_normal , word);			   		
	
	}
	
	
	protected void send_customer(byte[] prt_code_buffer, String in_String) {
		// TODO Auto-generated method stub
		int i;
		CharSequence t =  (CharSequence)in_String;
		char[] text = new char[t.length()];	//声明一个和所输入字符串同样长度的字符数组
		for (i=0; i<t.length(); i++) {
			text[i] = t.charAt(i);		//把CharSequence中的charAt传入刚声明的字符数组中
		}
		try {
			byte[] buffer = prt_code_buffer;//发送头;
			mOutputStream.write(buffer);
			mOutputStream.write(new String(text).getBytes("gb2312"));	//把字符数组变成byte型发送
			byte[] buffere = {0x0d};//发送尾;
			mOutputStream.write(buffere);			
		} catch (IOException e) {
			System.out.println("send customer failed");
		}		
	}
	
	
	@Override  
    protected void onRestoreInstanceState(Bundle savedInstanceState) {  
        // TODO Auto-generated method stub  
        super.onRestoreInstanceState(savedInstanceState);  
        Log.i("info", "onRestoreInstanceState");  
    }  
      
    @Override  
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
        // TODO Auto-generated method stub  
        super.onActivityResult(requestCode, resultCode, data);  
        Log.i("info", "onActivityResult");  
    }  
      
    @Override  
    protected void onSaveInstanceState(Bundle outState) {  
        // TODO Auto-generated method stub  
        super.onSaveInstanceState(outState);  
        Log.i("info", "onSaveInstanceState");  
    }  
      
    @Override  
    protected void onStart() {  
        // TODO Auto-generated method stub  
        super.onStart();  
        Log.i("info", "onStart");  
    }  
  
    @Override  
    protected void onRestart() {  
        // TODO Auto-generated method stub  
        super.onRestart();  
        Log.i("info", "onRestart");  
    }  
  
 
    @Override  
    protected void onPause() {  
        // TODO Auto-generated method stub  
        super.onPause();  
        ref_if = false;
        Log.i("info", "onPause");  
    }  
  
    @Override  
    protected void onStop() {  
        // TODO Auto-generated method stub  
        super.onStop();  
        ref_if = false;
        Log.i("info", "onStop");  
    }  
  
    @Override  
    protected void onDestroy() {  
        // TODO Auto-generated method stub  
        super.onDestroy();  
        Log.i("info", "onDestroy");  
    }  
  
    @Override  
    public void onLowMemory() {  
        // TODO Auto-generated method stub  
        super.onLowMemory();  
        //当系统内存不足时 才会调用  但不一定会百分百调用  如果能及时调用则会调用  可能在没用调用之前就将程序关闭了。  
        Log.i("info", "onLowMemory");  
    }  
  
    @Override  
    public void onBackPressed() {  
        // TODO Auto-generated method stub  
        super.onBackPressed();  
        
        ref_if = false;
        Log.i("info", "onBackPressed");  
        //  
    }  
  
    @Override  
    public void finish() {  
        // TODO Auto-generated method stub  
        super.finish();  
        //要关闭Activity 所以才要调用finish()方法  
        ref_if = false;
        Log.i("info", "finish");  
    }  
 
    
    @Override  
    public boolean onTouchEvent(MotionEvent event) {            
        // 按下时清理之前的记录  
        if (event.getAction() == MotionEvent.ACTION_DOWN) {  
            mRecordMap.clear();  
        }            
        return mGestureDetector.onTouchEvent(event);  
    }  
    
    private class DefaultGestureListener extends SimpleOnGestureListener {  
        // 滑动时触发  
        @Override  
        public boolean onScroll(MotionEvent e1, MotionEvent e2,  
                float distanceX, float distanceY) {  
            /*
             * 向上滑 Y 是正数
             * 向下滑 Y 是负数
             * 
             * 向左滑 X 是正数	值要比较大才是大滑动
             * 向右滑 X 是负数
             */  
        	if (distanceX > 15) {
        		TABLE_LV.setVisibility(View.GONE);
        		INOUTPIC.setBackgroundResource(drawable.in2out);
        		showornot = false;
			}
        	if (distanceX < -15) {
        		TABLE_LV.setVisibility(View.VISIBLE);
        		INOUTPIC.setBackgroundResource(drawable.out2in);
        		showornot = true;
			}
            return super.onScroll(e1, e2, distanceX, distanceY);  
        }  
    }
    
    
	protected void Save_SharePreference() {
		// TODO Auto-generated method stub
		progressDialog("正在处理结账打印           ", "请稍等......");		
     	insert_Thread thread= new insert_Thread();
     	thread.start();		
	}	
	/***************     以下是一个带进度条的对话框    **************************************/
	ProgressDialog progressDialog;

	private void progressDialog(String title, String message) {
		// TODO Auto-generated method stub
	     progressDialog = new ProgressDialog(Table2.this);
	     progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
	     progressDialog.setMessage(message);
	     progressDialog.setTitle(title);
	     progressDialog.setProgress(0);
	     progressDialog.setMax(100);
	     progressDialog.setCancelable(false);
	     progressDialog.show();
	}

	//用来查询进度条的值！大于100就把进度条Cancel掉
    Handler handler = new Handler(){
    	  @Override
    	  public void handleMessage(Message msg) {
    		  // TODO Auto-generated method stub
    		  if(msg.what>=100){
    			  progressDialog.cancel();
    	       }
    		  progressDialog.setProgress(msg.what);
    		  super.handleMessage(msg);
    	  }
    };

	
//创建一个进程！用来后台加载数据
    class insert_Thread extends Thread{
        public void run(){      	
			handler.sendEmptyMessage(1);	//进度条进度

			
			SerialPort mSerialPort = null;		//串口设备描述

	   	    int	   TTY_BPS = 9600;			//串口的初始信息！只在安装后第一次有用！以后会从xml中读出配置信息
	   		String TTY_DEV = "/dev/ttymxc2";
	   		String	SPF_Prt1_bt	=	"SPF_Prt1_bt";
	   		String	SPF_Prt2_bt	=	"SPF_Prt2_bt";
	   		String	SPF_Prt3_bt	=	"SPF_Prt3_bt";			   		
	   		String	SPF_Com_1	=	"SPF_Com_1";
			String	SPF_Com_2	=	"SPF_Com_2";
			String	SPF_Com_3	=	"SPF_Com_3";

			
			
	   		String[] btl_String = getResources().getStringArray(R.array.botelv);

			SharedPreferences settings = getSharedPreferences("Prt_Setup_SharedPreferences", 0);		
			String	SPF_ET_1_1	=	"SPF_ET_1_1";
			String	SPF_ET_1_2	=	"SPF_ET_1_2";
			String	SPF_ET_1_3	=	"SPF_ET_1_3";
			String	SPF_ET_2_1	=	"SPF_ET_2_1";
			String	SPF_ET_2_2	=	"SPF_ET_2_2";
			String	SPF_ET_2_3	=	"SPF_ET_2_3";
			String	SPF_ET_2_4	=	"SPF_ET_2_4";
			
			String COM_1 = settings.getString(SPF_Com_1, null);
			String COM_2 = settings.getString(SPF_Com_2, null);
			String COM_3 = settings.getString(SPF_Com_3, null);
	        Log.i("info", "COM = "+ COM_1 + COM_2 + COM_3);  

			if (COM_1.trim().equals("ZhuDa") ||COM_1.trim().equals("BingYong")) {
				TTY_DEV = "/dev/ttymxc4";
				TTY_BPS = settings.getInt(SPF_Prt1_bt, 0);
			    Integer intObjj = new Integer(btl_String[TTY_BPS]);
			    TTY_BPS = intObjj.intValue();	
			} else {
				if (COM_2.trim().equals("ZhuDa") ||COM_2.trim().equals("BingYong") ) {
					TTY_DEV = "/dev/ttymxc3";
					TTY_BPS = settings.getInt(SPF_Prt2_bt, 0);
				    Integer intObjj = new Integer(btl_String[TTY_BPS]);
				    TTY_BPS = intObjj.intValue();
				} else {
					if (COM_3.trim().equals("ZhuDa")|| COM_3.trim().equals("BingYong")) {
						TTY_DEV = "/dev/ttymxc2";
						TTY_BPS = settings.getInt(SPF_Prt3_bt, 0);
					    Integer intObjj = new Integer(btl_String[TTY_BPS]);
					    TTY_BPS = intObjj.intValue();
					} else {
						
					}
				}
			}
	        Log.i("info", "TTY_DEV = "+ TTY_DEV); 
	        
			try {
				mSerialPort = new SerialPort(new File(TTY_DEV), TTY_BPS, 0);
			} catch (SecurityException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}					
			mOutputStream = mSerialPort.getOutputStream();	
	   		
	   		get_SharePerference();
	   		
			print_String(Check_b1_4,Check_b2_1,Check_b2_2,settings.getString(SPF_ET_2_1, null));
			print_String(Check_b1_5,false,false,settings.getString(SPF_ET_2_2, null));
			print_String(Check_b1_6,false,false,settings.getString(SPF_ET_2_3, null));
			print_String(true,false,false," 桌台：" + CheckTableNum  );
			print_String(true,false,false," 结账单号  "+ CheckNum );
			print_String(true,false,false,"===============================");
			print_String(true,false,false,CheckContent);
			try {
				String[] sell_number = {CheckDanhao};
				Cursor cursor = db.rawQuery("select * from lfcy_base_sellinf where cSellNo= ?", sell_number);
				int number = 0;
				while(cursor.moveToNext()) 
				{
					number ++;
					String SdishName = cursor.getString(cursor.getColumnIndex("cDishName"));
					String Snum		 = cursor.getString(cursor.getColumnIndex("cDishQty"));
					String Sprice 	 = cursor.getString(cursor.getColumnIndex("fDishPrice"));
					String Unit 	 = cursor.getString(cursor.getColumnIndex("cDishUnitName"));
					
	   				print_String(true,false,false,number+"    "+ SdishName +"     "+Snum +Unit+"    "+Sprice+"元" );
				}		
				print_String(true,false,false,"===============================");
				print_String(true,false,false," 总价：	     "+ CheckXiaoFeiZongJia +"元");				   				
				print_String(true,false,false," 加收：	     "+ CheckJiaShou +"元");
				print_String(true,false,false," 应收：	     "+ CheckYingShou +"元" );
				print_String(true,Check_b2_9,Check_b2_10," 现金：	     "+ CheckXianJinShiSHou +"元" );
				print_String(true,Check_b2_11,Check_b2_12," 找零：	     "+ CheckZhaoLing +"元" );
				print_String(Check_b2_5,false,Check_b2_6," 操作员："+ CheckUser);
				print_String(Check_b2_7,false,Check_b2_8," 时间:"+ CheckDateTime);
				print_String(Check_b1_7,false,false,settings.getString(SPF_ET_2_4, null));
				print_String(true,false,false," ");
				print_String(true,false,false," ");
				print_String(true,false,false," ");
				print_String(true,false,false," ");
				print_String(true,false,false," ");
				mSerialPort.close();
			} catch (Exception e) {
				// TODO: handle exception
			}

	        handler.sendEmptyMessage(100);
        }
    };

	private void get_SharePerference() {
		SharedPreferences settings = getSharedPreferences("Prt_Setup_SharedPreferences", 0);		
		
		
		String	SPF_CHECKBOX_1_1	=	"SPF_CHECKBOX_1_1";
		String	SPF_CHECKBOX_1_2	=	"SPF_CHECKBOX_1_2";
		String	SPF_CHECKBOX_1_3	=	"SPF_CHECKBOX_1_3";
		String	SPF_CHECKBOX_1_4	=	"SPF_CHECKBOX_1_4";
		String	SPF_CHECKBOX_1_5	=	"SPF_CHECKBOX_1_5";
		String	SPF_CHECKBOX_1_6	=	"SPF_CHECKBOX_1_6";
		String	SPF_CHECKBOX_1_7	=	"SPF_CHECKBOX_1_7";

		String	SPF_CHECKBOX_2_1	=	"SPF_CHECKBOX_2_1";
		String	SPF_CHECKBOX_2_2	=	"SPF_CHECKBOX_2_2";
		String	SPF_CHECKBOX_2_3	=	"SPF_CHECKBOX_2_3";
		String	SPF_CHECKBOX_2_4	=	"SPF_CHECKBOX_2_4";
		String	SPF_CHECKBOX_2_5	=	"SPF_CHECKBOX_2_5";
		String	SPF_CHECKBOX_2_6	=	"SPF_CHECKBOX_2_6";
		String	SPF_CHECKBOX_2_7	=	"SPF_CHECKBOX_2_7";
		String	SPF_CHECKBOX_2_8	=	"SPF_CHECKBOX_2_8";
		String	SPF_CHECKBOX_2_9	=	"SPF_CHECKBOX_2_9";
		String	SPF_CHECKBOX_2_10	=	"SPF_CHECKBOX_2_10";
		String	SPF_CHECKBOX_2_11	=	"SPF_CHECKBOX_2_11";
		String	SPF_CHECKBOX_2_12	=	"SPF_CHECKBOX_2_12";

		String	SPF_CHECKBOX_3_1	=	"SPF_CHECKBOX_3_1";
		String	SPF_CHECKBOX_3_2	=	"SPF_CHECKBOX_3_2";
		String	SPF_CHECKBOX_3_3	=	"SPF_CHECKBOX_3_3";
		String	SPF_CHECKBOX_3_4	=	"SPF_CHECKBOX_3_4";
		String	SPF_CHECKBOX_3_5	=	"SPF_CHECKBOX_3_5";
		String	SPF_CHECKBOX_3_6	=	"SPF_CHECKBOX_3_6";
		String	SPF_CHECKBOX_3_7	=	"SPF_CHECKBOX_3_7";
		String	SPF_CHECKBOX_3_8	=	"SPF_CHECKBOX_3_8";
		String	SPF_CHECKBOX_3_9	=	"SPF_CHECKBOX_3_9";
		String	SPF_CHECKBOX_3_10	=	"SPF_CHECKBOX_3_10";
		String	SPF_CHECKBOX_3_11	=	"SPF_CHECKBOX_3_11";
		String	SPF_CHECKBOX_3_12	=	"SPF_CHECKBOX_3_12";
		
//		settings.getString(SPF_ET_1_1, null) ;
//		settings.getString(SPF_ET_1_2, null) ;
//		settings.getString(SPF_ET_1_3, null) ;
//	    CheckTitle = settings.getString(SPF_ET_2_1, null) ;
//		settings.getString(SPF_ET_2_2, null) ;
//		settings.getString(SPF_ET_2_3, null) ;
//		settings.getString(SPF_ET_2_4, null) ;
	
		Check_b1_1 = settings.getBoolean(SPF_CHECKBOX_1_1, false);
		Check_b1_2 = settings.getBoolean(SPF_CHECKBOX_1_2, false);
		Check_b1_3 = settings.getBoolean(SPF_CHECKBOX_1_3, false);
		Check_b1_4 = settings.getBoolean(SPF_CHECKBOX_1_4, false);
		Check_b1_5 = settings.getBoolean(SPF_CHECKBOX_1_5, false);
		Check_b1_6 = settings.getBoolean(SPF_CHECKBOX_1_6, false);
		Check_b1_7 = settings.getBoolean(SPF_CHECKBOX_1_7, false);

		Check_b2_1 = settings.getBoolean(SPF_CHECKBOX_2_1, false);
		Check_b2_2 = settings.getBoolean(SPF_CHECKBOX_2_2, false);
		Check_b2_3 = settings.getBoolean(SPF_CHECKBOX_2_3, false);
		Check_b2_4 = settings.getBoolean(SPF_CHECKBOX_2_4, false);
		Check_b2_5 = settings.getBoolean(SPF_CHECKBOX_2_5, false);
		Check_b2_6 = settings.getBoolean(SPF_CHECKBOX_2_6, false);
		Check_b2_7 = settings.getBoolean(SPF_CHECKBOX_2_7, false);
		Check_b2_8 = settings.getBoolean(SPF_CHECKBOX_2_8, false);
		Check_b2_9 = settings.getBoolean(SPF_CHECKBOX_2_9, false);
		Check_b2_10= settings.getBoolean(SPF_CHECKBOX_2_10, false);
		Check_b2_11= settings.getBoolean(SPF_CHECKBOX_2_11, false);
		Check_b2_12= settings.getBoolean(SPF_CHECKBOX_2_12, false);

		Check_b3_1 = settings.getBoolean(SPF_CHECKBOX_3_1, false);
		Check_b3_2 = settings.getBoolean(SPF_CHECKBOX_3_2, false);
		Check_b3_3 = settings.getBoolean(SPF_CHECKBOX_3_3, false);
		Check_b3_4 = settings.getBoolean(SPF_CHECKBOX_3_4, false);
		Check_b3_5 = settings.getBoolean(SPF_CHECKBOX_3_5, false);
		Check_b3_6 = settings.getBoolean(SPF_CHECKBOX_3_6, false);
		Check_b3_7 = settings.getBoolean(SPF_CHECKBOX_3_7, false);
		Check_b3_8 = settings.getBoolean(SPF_CHECKBOX_3_8, false);
		Check_b3_9 = settings.getBoolean(SPF_CHECKBOX_3_9, false);
		Check_b3_10= settings.getBoolean(SPF_CHECKBOX_3_10, false);
		Check_b3_11= settings.getBoolean(SPF_CHECKBOX_3_11, false);
		Check_b3_12= settings.getBoolean(SPF_CHECKBOX_3_12, false);
	}
	/***************     以上是一个进度条    **************************************/

   
}